#!/bin/sh
tmpdir="@KEDR_TEST_PREFIX_TEMP_SESSION@/kedr_trace_simple_ordering"
debugfs_mount_point="${tmpdir}/debugfs"
trace_file="${debugfs_mount_point}/kedr_tracing/trace"
trace_file_copy="@CMAKE_CURRENT_BINARY_DIR@/trace.txt"

trace_module="@CMAKE_CURRENT_BINARY_DIR@/../../kedr_trace.ko"
module="@CMAKE_CURRENT_BINARY_DIR@/module/simple_ordering_module.ko"

mkdir -p "${debugfs_mount_point}"

if ! mount -t debugfs debugfs "${debugfs_mount_point}"; then
	printf "Cannot mount debugfs filesystem.\n"
	exit 1
fi

if ! insmod "${trace_module}"; then
	printf "Cannot load kedr trace module.\n"
	umount "${debugfs_mount_point}"
	exit 1
fi


if ! insmod "${module}"; then
	printf "Cannot load module for testing.\n"
	rmmod "${trace_module}"
	umount "${debugfs_mount_point}"
	exit 1
fi


# Because standard opening trace file will block read at the end of the trace,
# use background mode for copiing file.
cat ${trace_file} > ${trace_file_copy} &
capture_pid=$!
sleep 0.5
kill $capture_pid
wait $capture_pid

if ! rmmod "${module}"; then
	printf "Cannot unload module for testing.\n"
	#Unloading of kedr_trace module will definitely fail
	umount "${debugfs_mount_point}"
	exit 1
fi

if ! rmmod "${trace_module}"; then
	printf "Cannot unload kedr trace module.\n"
	umount "${debugfs_mount_point}"
	exit 1
fi

if ! umount "${debugfs_mount_point}"; then
	printf "Failed to unmount debugfs filesystem."
fi

# Verify trace
LC_ALL=C awk -f "@CMAKE_CURRENT_SOURCE_DIR@/../verify_trace_format.awk" \
    "${trace_file_copy}"
if test $? -ne 0; then
	printf "Trace file has incorrect format.\n"
	exit 1
fi

LC_ALL=C awk -f "@CMAKE_CURRENT_SOURCE_DIR@/verify_trace.awk" \
    "${trace_file_copy}"
if test $? -ne 0; then
	printf "Trace file is inconsistent.\n"
	exit 1
fi
